package com.xiaoxin.executor.config;

import com.xiaoxin.executor.batch.listener.MyJobListener;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.repository.support.JobRepositoryFactoryBean;
import org.springframework.batch.core.scope.StepScope;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;


/**
 * SpringBatch开启批处理配置
 */

@EnableBatchProcessing
@Configuration
public class SpringBatchConfig {

    @Bean
    public StepScope stepScope() {
        return new StepScope();
    }

    /**
     * JobRepository定义：Job的注册容器以及和数据库打交道（事务管理等）
     *
     * @param dataSource
     * @param transactionManager
     * @return
     * @throws Exception
     */

    @Bean
    public JobRepository myJobRepository(@Qualifier(value = "masterDataSource") DataSource dataSource,
                                         PlatformTransactionManager transactionManager) throws Exception {
        JobRepositoryFactoryBean jobRepositoryFactoryBean = new JobRepositoryFactoryBean();
        jobRepositoryFactoryBean.setDatabaseType("mysql");
        jobRepositoryFactoryBean.setTransactionManager(transactionManager);
        jobRepositoryFactoryBean.setDataSource(dataSource);
        return jobRepositoryFactoryBean.getObject();
    }

    /**
     * jobLauncher定义：job的启动器,绑定相关的jobRepository
     *
     * @param dataSource
     * @param transactionManager
     * @return
     * @throws Exception <p>
     *                   注册job监听器
     */

    @Bean
    public SimpleJobLauncher myJobLauncher(@Qualifier(value = "masterDataSource") DataSource dataSource,
                                           PlatformTransactionManager transactionManager) throws Exception {
        SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
        // 设置jobRepository
        jobLauncher.setJobRepository(myJobRepository(dataSource, transactionManager));
        return jobLauncher;
    }

    /**
     * 注册job监听器
     *
     * @return
     */

    @Bean
    public MyJobListener myJobListener() {
        return new MyJobListener();
    }

}
